/* eslint-disable react/jsx-key */
import React, { useEffect, useRef, useState } from 'react';
import { Switch, Modal, Tooltip, Form, Popconfirm, message } from 'antd';
import { connect, useRequest } from 'umi';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { postFetch, getFetch } from '@/utils/doFetch';
import { stopsettle, companydetail, company } from '@/services/business';
import { PlusOutlined, ExportOutlined, ImportOutlined } from '@ant-design/icons';
import moment from 'moment';
import * as basic from '@/services/basic';
import CompanyName from '@/components/CompanyName';

// import Uploadcom from './uploadcom';

let Voucher = (props) => {
  const { user, dispatch } = props,
    defaultFields = {
      company_ids: {
        value: null,
        type: 'checktable',
        title: '代账公司',
        name: ['company_ids'],
        columns: [
          {
            title: '业务编号',
            dataIndex: 'code',
            key: 'code',
            search: false,
          },
          {
            title: '公司名称',
            width: 260,
            dataIndex: 'name',
            key: 'name',
            copyable: true,
          },
          {
            title: '月收费',
            dataIndex: 'unit_price',
            key: 'unit_price',
            search: false,
          },
          {
            title: '公司法人',
            dataIndex: 'legal_person',
            key: 'legal_person',
            search: false,
          },
          {
            title: '联系人',
            dataIndex: 'customer_name',
            key: 'customer_name',
            ellipsis: true,
          },
          {
            title: '联系人手机号',
            width: 120,
            dataIndex: 'customer_phone',
            key: 'customer_phone',
            render: (_, row) => (
              <Tooltip title={row.customer_phone}>
                <a href={`tel:${row.customer_phone}`} className="oneline">
                  {row.customer_phone}
                </a>
              </Tooltip>
            ),
          },
          {
            title: '区域名称',
            dataIndex: 'area_name',
            key: 'area_name',
            search: false,
          },
          {
            title: '接单人',
            dataIndex: 'user_name',
            key: 'user_name',
            search: false,
          },
          {
            title: '促单人',
            dataIndex: 'promoter_user_name',
            key: 'promoter_user_name',
            search: false,
          },
          {
            title: '公司类型',
            dataIndex: 'classify_name',
            key: 'classify_name',
            search: false,
          },
        ],
        rowKey: 'id',
        rowName: 'name',
        required: true,
        path: '/wbn-api/company',
        extraparams: {
          account_user_id: user.currentUser.id,
          type: -1,
          status: 'completed',
        },
        col: { span: 24 },
      },
      voucher_date: {
        value: null,
        type: 'datepicker',
        title: '凭证月份',
        name: ['voucher_date'],
        format: 'YYYY-MM',
        required: true,
        picker: 'month',
        col: { span: 24 },
      },
      // add
      review_user_id: {
        value: null,
        type: 'select',
        title: '会计复核',
        name: ['review_user_id'],
        required: true,
        options: {
          database: basic.user,
          params: { is_all: 1, role_type: 3 },
        },
        col: { span: 24 },
      },

      is_delay: {
        value: null,
        type: 'radio',
        title: '是否延期',
        name: ['is_delay'],
        required: true,
        col: { span: 24 },
        options: [
          {
            label: '正常',
            value: false,
          },
          {
            label: '延期',
            value: true,
          },
        ],
      },
    };
  let actionRef = useRef(),
    ChildRef = null;
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({}),
    [formRef] = Form.useForm(),
    [key, setkey] = useState('1');

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = [
    {
      title: '业务编号',
      dataIndex: 'service_code',
      key: 'service_code',
      search: false,
    },
    {
      title: '复核会计',
      dataIndex: 'review_user_name',
      key: 'review_user_name',
      search: false,
    },
    {
      title: '记账会计',
      dataIndex: 'account_name',
      key: 'account_name',
      search: false,
    },
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
          reload={reload}
        />
      ),
    },
    {
      title: '公司类型',
      dataIndex: 'classify_name',
      key: 'classify_name',
      search: false,
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '记账提成',
      dataIndex: 'account_take',
      key: 'account_take',
      ellipsis: true,
    },
    {
      title: '报送日期',
      dataIndex: 'submit_date',
      key: 'submit_date',
      render: (text, row) => {
        return (
          <span className="oneline">
            {row.submit_date ? moment(row.submit_date).format('YYYY-MM-DD') : ''}
          </span>
        );
      },
    },
    {
      title: '凭证日期',
      dataIndex: 'voucher_date',
      key: 'voucher_date',
      valueType: 'dateMonth',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      search: false,
      render: (text, row) => {
        return (
          <span
            style={{
              color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
              cursor: 'pointer',
            }}
            onClick={() => {
              if (row?.status?.indexOf('refuse') != -1) {
                Modal.info({
                  title: '拒绝原因',
                  content: row.refuse_message,
                  maskClosable: true,
                });
              }
            }}
          >
            {row.status == 'cache'
              ? '暂存'
              : row.status == 'pending'
              ? '复核中'
              : row.status == 'refuse'
              ? '拒绝'
              : row.status == 'review'
              ? '审核完成'
              : row.status == 'completed '
              ? '已入库'
              : ''}
          </span>
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 90,
      render: (text, row, _, action) => extraAction(text, row, _, action),
    },
  ];

  function extraAction(text, record, _, action) {
    return [
      <a
        disabled={['refuse', 'cache'].indexOf(record.status) == -1}
        onClick={() => {
          if (['refuse', 'cache'].indexOf(record.status) == -1) {
            return;
          }
          ciftype({
            val: 'edit',
            id: record.id,
            title: '修改凭证',
          });
          cf(() => {
            for (let i in defaultFields) {
              defaultFields[i].value = record[i];
              if (i.indexOf('password') != -1 || i.indexOf('company_ids') != -1) {
                defaultFields[i].hides = true;
              }
            }
            return { ...defaultFields };
          });
          cvs(true);
        }}
      >
        修改
      </a>,
      <Popconfirm
        disabled={['refuse', 'cache'].indexOf(record.status) == -1}
        title="确认删除该凭证？"
        onConfirm={() => {
          dispatch({
            type: 'customer/deletevoucher',
            payload: record.id,
          }).then((res) => {
            if (res.code == 0) {
              message.success('操作成功');
              reload();
              cvs(false);
            }
          });
        }}
      >
        <a
          disabled={['refuse', 'cache'].indexOf(record.status) == -1}
          style={{ color: ['refuse', 'cache'].indexOf(record.status) == -1 ? '#ddd' : 'red' }}
        >
          删除
        </a>
      </Popconfirm>,
    ];
  }

  let saveData = (values, fn) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      dispatch({
        type: 'customer/addvoucher',
        payload: { ...values },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'edit') {
      dispatch({
        type: 'customer/editvoucher',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  let extra = (
    <div className="center" style={{ gap: 12 }}>
      <div
        className="action"
        title="新增"
        onClick={() => {
          cvs(true);
          cf((fields) => {
            for (let i in defaultFields) {
              defaultFields[i].value = null;
              defaultFields[i].hides = false;
            }
            return { ...defaultFields };
          });
          ciftype({
            val: 'add',
            title: '新增凭证',
          });
        }}
      >
        <PlusOutlined />
      </div>
      <Tooltip title="导出凭证">
        <div
          className="action"
          onClick={() => {
            const hide = message.loading('正在导出..', 0);
            getFetch({
              url: '/wbn-api/voucher/download_voucher',
              params: { is_all: 1 },
            }).then((res) => {
              window.open(res?.data);
              hide();
            });
          }}
        >
          <ExportOutlined />
        </div>
      </Tooltip>
    </div>
  );

  const extras = !props.user.currentUser.is_admin
    ? { account_user_id: props.user.currentUser.id }
    : {};

  return (
    <div className="nopa autotable">
      <AutoTable
        tabList={[
          {
            key: '1',
            tab: '正常',
          },
          {
            key: '2',
            tab: '逾期',
          },
        ]}
        onTabChange={(val) => {
          setkey(val);
        }}
        pagetitle={props.route.name}
        pageextra={extra}
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        extraparams={{ is_delay: key === '2', ...extras }}
        // tabBarExtraContent={
        //   <div className="center" style={{ gap: 12 }}>
        //     <a
        //       rel="noreferrer"
        //       onClick={() => {
        //         let token = localStorage.getItem('TOKEN');

        //         fetch('/wbn-api/voucher/download_import_template', {
        //           headers: {
        //             'Content-Type': 'application/json',
        //             Accept: 'application/json',
        //             Authorization: token,
        //           },
        //         })
        //           .then((response) => response.blob())
        //           .then((blob) => {
        //             // 创建一个 Blob 对象
        //             const blobObject = new Blob([blob]);

        //             // 创建一个下载链接
        //             const downloadLink = document.createElement('a');
        //             const objectURL = URL.createObjectURL(blobObject);

        //             // 设置链接属性
        //             downloadLink.href = objectURL;
        //             downloadLink.download = '凭证导入模板.xlsx'; // 例如：'downloaded_file.txt'

        //             // 模拟点击下载链接
        //             document.body.appendChild(downloadLink);
        //             downloadLink.click();

        //             // 移除链接元素
        //             document.body.removeChild(downloadLink);

        //             // 释放对象 URL
        //             URL.revokeObjectURL(objectURL);
        //           })
        //           .catch((error) => console.error('下载失败:', error));
        //       }}
        //     >
        //       下载凭证模板
        //     </a>
        //     <a
        //       onClick={() => {
        //         cvs(true);
        //         ciftype({
        //           val: 'inside',
        //           title: '凭证导入',
        //         });
        //       }}
        //     >
        //       凭证导入
        //     </a>
        //   </div>
        // }
        path="/wbn-api/voucher"
      />

      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        destroyOnClose={true}
        style={{ top: 20 }}
        width={1366}
      >
        {iftype.val == 'inside' ? (
          <div>
            {/* <Uploadcom
              reload={() => {
                reload();
                cvs(false);
              }}
             /> */}
          </div>
        ) : (
          <InitForm
            formRef={formRef}
            fields={fields}
            submitData={(values, fn) => {
              saveData(values, fn);
            }}
            onChange={(changedValues, allValues) => {}}
            submitting={
              props.loading.effects['customer/addvoucher'] ||
              props.loading.effects['customer/editvoucher'] ||
              !vs
            }
            halfsave={true}
          />
        )}
      </Modal>
    </div>
  );
};

export default connect(({ user, loading }) => ({
  user,
  loading,
}))(Voucher);
